//
//  QWSearchBar.m
//  MySearchBar
//
//  Created by August on 14-7-28.
//  Copyright (c) 2014年 August. All rights reserved.
//

#import "QWSearchBar.h"

#define _SYSTERVERSION_  [[[UIDevice currentDevice] systemVersion] floatValue]

#ifndef RGB
#define RGB(r, g, b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1]
#endif

@interface QWSearchBar() {
    BOOL _showPlaceholderCenter;
}
@end

@implementation QWSearchBar

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self inintConfig];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self inintConfig];
    }
    return self;
}

- (void)inintConfig
{
    _showPlaceholderCenter = YES;

    self.backgroundColor = [UIColor clearColor];

    self.textField = [[QWSearchBarTextField alloc] initWithFrame:self.bounds];
    [self addSubview:self.textField];
    self.textField.delegate = self;

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textFieldTextDidChanged:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:self.textField];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setTopSpace:(CGFloat)topSpace
{
    _topSpace = topSpace;

    [self setNeedsLayout];
}

- (void)setLeadingSpace:(CGFloat)leadingSpace
{
    _leadingSpace = leadingSpace;
    
    [self setNeedsLayout];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGRect rect = CGRectInset(self.bounds, _leadingSpace, _topSpace);
    self.textField.frame = rect;
}

#pragma mark -
#pragma mark UITextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([self.delegate respondsToSelector:@selector(QWSearchBarShouldBeginEditing:)]) {
        return [self.delegate QWSearchBarShouldBeginEditing:self];
    }
    
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (_showPlaceholderCenter) {
        _showPlaceholderCenter = NO;
        [UIView animateWithDuration:0.25
                              delay:0.0f
                            options:UIViewAnimationOptionBeginFromCurrentState
                         animations:^{
                             [self layoutIfNeeded];
                         }
                         completion:nil
         ];
    }

    if ([self.delegate respondsToSelector:@selector(QWSearchBarDidBeginEditing:)]) {
        [self.delegate QWSearchBarDidBeginEditing:self];
    }
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if ([self.delegate respondsToSelector:@selector(QWSearchBarShouldEndEditing:)]) {
        return [self.delegate QWSearchBarShouldEndEditing:self];
    }

    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (!_showPlaceholderCenter && [self.text length] == 0) {
        _showPlaceholderCenter = YES;
        [UIView animateWithDuration:0.25
                              delay:0.0f
                            options:UIViewAnimationOptionBeginFromCurrentState
                         animations:^{
                             [self layoutIfNeeded];
                         }
                         completion:nil
         ];
    }

    if ([self.delegate respondsToSelector:@selector(QWSearchBarDidEndEditing:)]) {
        [self.delegate QWSearchBarDidEndEditing:self];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([self.delegate respondsToSelector:@selector(QWSearchBarSearchButtonClicked:)]) {
        [self.delegate QWSearchBarSearchButtonClicked:self];
    }
    
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([self.delegate respondsToSelector:@selector(QWSearchBar:shouldChangeTextInRange:replacementText:)]) {
        return [self.delegate QWSearchBar:self
                  shouldChangeTextInRange:range
                          replacementText:string];
    }
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if ([self.delegate respondsToSelector:@selector(QWSearchBarShouldClear:)]) {
        return [self.delegate QWSearchBarShouldClear:self];
    }
    
    return YES;
}

- (void)textFieldTextDidChanged:(NSNotification *)notify
{
    if ([self.delegate respondsToSelector:@selector(QWSearchBar:textDidChange:)]) {
        [self.delegate QWSearchBar:self textDidChange:self.textField.text];
    }
}

#pragma mark -
#pragma mark 模仿UISearchBar的行为

- (BOOL)becomeFirstResponder {
    if ([_textField becomeFirstResponder]) {
//        [self setShowsCancelButton:YES animated:YES];
    }
    return YES;
}

- (BOOL)resignFirstResponder {
    if ([_textField resignFirstResponder]) {
        //[self setShowsCancelButton:NO animated:YES];
    }
    return YES;
}

- (UIKeyboardType)keyboardType
{
    return _textField.keyboardType;
}

- (void)setKeyboardType:(UIKeyboardType)type
{
    _textField.keyboardType = type;
}

- (UIKeyboardAppearance)keyboardAppearance
{
    return _textField.keyboardAppearance;
}

- (void)setKeyboardAppearance:(UIKeyboardAppearance)keyboardAppearance
{
    _textField.keyboardAppearance = keyboardAppearance;
}

- (UITextFieldViewMode)clearButtonMode
{
    return _textField.clearButtonMode;
}

- (void)setClearButtonMode:(UITextFieldViewMode)clearButtonMode
{
    _textField.clearButtonMode = clearButtonMode;
}

- (NSString *)placeholder
{
    return _textField.placeholder;
}

- (void)setPlaceholder:(NSString *)placeholder
{
    _textField.placeholder = placeholder;
}

- (NSString *)text
{
    return _textField.text;
}

- (void)setText:(NSString *)text
{
    _textField.text = text;
}

- (UIFont *)font
{
    return _textField.font;
}

- (void)setFont:(UIFont *)font
{
    _textField.font = font;
}

- (UIColor *)textColor
{
    return _textField.textColor;
}

- (void)setTextColor:(UIColor *)textColor
{
    _textField.textColor = textColor;
}

- (UIColor *)searchBarBackgroundColor
{
    return _textField.backgroundColor;
}

- (void)setSearchBarBackgroundColor:(UIColor *)searchBarBackgroundColor
{
    _textField.backgroundColor = searchBarBackgroundColor;
}

- (UIImage *)leftImage
{
    return _textField.leftImage;
}

- (void)setLeftImage:(UIImage *)leftImage
{
    [_textField setLeftImage:leftImage];
}

- (UIColor *)placeholderColor
{
    return _textField.placeholderColor;
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    [_textField setPlaceholderColor:placeholderColor];
}

- (UIImage *)clearButtonImage
{
    return _textField.clearButtonImage;
}

- (void)setClearButtonImage:(UIImage *)clearButtonImage
{
    [_textField setClearButtonImage:clearButtonImage];
}

@end

@implementation QWSearchBarTextField
{
    UIImageView *_clearButtonImageView;
    UIImageView *_leftImageView;
    UILabel *_placeholderLabel;
    NSString *_placeholderStr;
}

#pragma mark - init/Config methods

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self inintConfig];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self inintConfig];
    }
    return self;
}

- (void)inintConfig
{
    self.backgroundColor = [UIColor colorWithRed:39/255.0 green:177/255.0 blue:234/255.0 alpha:1];
    self.layer.cornerRadius = 4.0f;
    
    UIButton *clearButton = [self valueForKey:@"_clearButton"];
    clearButton.imageEdgeInsets = UIEdgeInsetsMake(-100, 0, 0, 0);
    [clearButton setBackgroundImage:nil forState:UIControlStateNormal];
    [clearButton setBackgroundImage:nil forState:UIControlStateHighlighted];
    _clearButtonImageView = [[UIImageView alloc] initWithFrame:clearButton.bounds];
    _clearButtonImageView.backgroundColor = [UIColor clearColor];
    [clearButton addSubview:_clearButtonImageView];
    
    self.leftViewMode = UITextFieldViewModeNever;
    self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    self.returnKeyType = UIReturnKeySearch;
}

#pragma mark - custom methods

- (void)setLeftImage:(UIImage *)leftImage
{
    _leftImage = leftImage;

    if (leftImage) {
        UIImageView *leftImgView = [[UIImageView alloc]
                                    initWithFrame:CGRectMake(20.0f,
                                                             0.0f,
                                                             leftImage.size.width + 10.0f,
                                                             leftImage.size.height)];
        leftImgView.image = leftImage;
        leftImgView.contentMode = UIViewContentModeCenter;
        leftImgView.tag = 8892;
        self.leftView = leftImgView;
        self.leftViewMode = UITextFieldViewModeAlways;
    } else {
        self.leftView = nil;
        self.leftViewMode = UITextFieldViewModeNever;
    }
}

- (void)setClearButtonImage:(UIImage *)clearButtonImage
{
    _clearButtonImage = clearButtonImage;
    _clearButtonImageView.image = _clearButtonImage;
}

- (void)drawPlaceholderInRect:(CGRect)rect
{
    UIColor *curColor = _placeholderColor ? _placeholderColor : [UIColor colorWithWhite:1 alpha:0.7];
    [curColor setFill];
    UIFont *font = self.font ? self.font : [UIFont systemFontOfSize:14.0f];
    rect.origin.y = (rect.size.height - font.lineHeight) / 2;
    rect.size.height = font.lineHeight + 4.0f;
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineBreakMode:NSLineBreakByTruncatingTail];

    [[self placeholder] drawInRect:rect
                    withAttributes:@{NSFontAttributeName : font,
                                     NSParagraphStyleAttributeName : paragraphStyle}];
}

- (CGRect)leftViewRectForBounds:(CGRect)bounds
{
    if (self.editing || [self.text length] > 0) {
        CGRect rect = [super leftViewRectForBounds:bounds];
        rect.origin.x += 5.0f;
        return rect;
    } else {
        CGRect rect = [super leftViewRectForBounds:bounds];
        
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineBreakMode:NSLineBreakByTruncatingTail];
        
        CGSize size = [self.placeholder boundingRectWithSize:CGSizeMake(self.bounds.size.width, 20.0f)
                                                     options:NSStringDrawingUsesLineFragmentOrigin
                                                  attributes:@{NSFontAttributeName : self.font,
                                                               NSParagraphStyleAttributeName : paragraphStyle}
                                                     context:nil].size;

        CGFloat totalWidth = size.width + self.leftView.frame.size.width;
        rect.origin.x += (self.bounds.size.width - totalWidth) / 2.0f + 6.5f;
        return rect;
    }
}

- (CGRect)clearButtonRectForBounds:(CGRect)bounds
{
    CGRect rect = [super clearButtonRectForBounds:bounds];
    rect.origin.x -= 2.0f;
    return rect;
}

@end
